<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2020/9/17
 * Time: 15:04
 */
namespace App\Api\Controllers\DaDa;


use App\Models\DadaConfig;
use App\Models\DadaMerchant;
use App\Models\DadaOrder;
use App\Models\DadaStore;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CancelController extends BaseController
{
    /**
     * 取消订单
     *
     * 在订单待接单或待取货情况下，调用此接口可取消订单
     * 取消费用说明：接单1 分钟以内取消不扣违约金；接单后1－15分钟内取消订单，运费退回。同时扣除2元作为给配送员的违约金； 配送员接单后15 分钟未到店，商户取消不扣违约金；
     * 系统取消订单说明：超过72小时未接单系统自动取消。每天凌晨2点，取消大于72小时未完成的订单
     * @param Request $request
     * @return string
     */
    public function orderFormalCancel(Request $request)
    {
        $token = $this->parseToken();
        $config_id = $request->post('configId', '1234'); //服务商配置id,不传走平台，1234
        $store_id = $request->post('storeId', ''); //门店id
        $order_id = $request->post('orderId', ''); //订单id
        $cancel_reason_id = $request->post('cancelReasonId', ''); //Integer,取消原因ID
        $cancel_reason = $request->post('cancel_reason', ''); //取消原因(当取消原因ID为其他时，此字段必填)

        $check_data = [
            'storeId' => '门店id',
            'orderId' => '第三方订单编号',
            'cancelReasonId' => '取消原因ID'
        ];
        $check = $this->check_required($request->except(['token']), $check_data);
        if ($check) {
            return json_encode([
                'status' => '2',
                'message' => $check
            ]);
        }

        $result_obj = DadaOrder::where('origin_id', $order_id)->first();
        if (!$result_obj) {
            return json_encode([
                'status' => '2',
                'message' => '取消订单,没有找到订单信息'
            ]);
        }

        if ($cancel_reason_id == '10000' && empty($cancel_reason)) {
            return json_encode([
                'status' => '2',
                'message' => '当取消原因ID为10000时，取消原因必填'
            ]);
        }

        $config_obj = DadaConfig::where('config_id', $config_id)->first();
        if (!$config_obj || empty($config_obj->app_key) || empty($config_obj->app_secret)) {
            return json_encode([
                'status' => '2',
                'message' => '达达配送参数未配置'
            ]);
        }

        $dada_merchant_obj = DadaMerchant::where('config_id', $config_id)
            ->where('status', 1)
            ->first();
        if (!$dada_merchant_obj) {
            return json_encode([
                'status' => '2',
                'message' => '达达商户尚未创建or状态异常'
            ]);
        }

        $app_key = $config_obj->app_key;
        $app_secret = $config_obj->app_secret;
        $source_id = $dada_merchant_obj->source_id; //商户id

        try {
            $requestData = [
                'order_id' => $order_id,
                'cancel_reason_id' => $cancel_reason_id
            ];
            if ($cancel_reason) $requestData['cancel_reason'] = $cancel_reason;

            Log::info('达达配送-取消订单');
            Log::info($requestData);
            $res_arr = $this->http_post($this->formalCancel, $app_key, $app_secret, $source_id, $requestData); //1-成功 2-失败
            Log::info($res_arr);

            //成功,更新达达配送订单表
            if ($res_arr['status'] == '1') {
                $result_arr = json_decode($res_arr['data'], true);
                if ($result_arr['status'] == 'success') {
                    $update_data = [
                        'deduct_fee' => $result_arr['result']['deduct_fee'],
                        'status_code' => 5
                    ];

                    $result = $result_obj->update($update_data);
                    if (!$result) {
                        return json_encode([
                            'status' => '2',
                            'message' => '取消订单,更新达达订单失败'
                        ]);
                    }

                    return json_encode([
                        'status' => '1',
                        'data' => $result_arr['result'],
                        'message' => $result_arr['msg'] ?? $this->getMessageByCode($result_arr['code'])
                    ]);
                }
            }

            return json_encode($res_arr);
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }



}
